package ltd.smallwang;

import java.util.LinkedList;

/**
 * @author justd
 * @date 2024-10-13 00:18
 */
public class Leetcode0151 {

  public String reverseWords(String s) {
    return method03(s);
  }

  private static String method03(String s) {
    boolean findNonZero = false;
    StringBuilder wordBuilder = new StringBuilder();
    StringBuilder result = new StringBuilder();
    for (int i = 0; i < s.length(); i++) {
      if (!findNonZero) {
        if (s.charAt(i) != ' ') {
          findNonZero = true;
          wordBuilder.append(s.charAt(i));
        }
        continue;
      }
      if (s.charAt(i) == ' ') {
        findNonZero = false;
        result.insert(0, wordBuilder + " ");
        wordBuilder.setLength(0);
      } else {
        wordBuilder.append(s.charAt(i));
      }
    }
    if (!wordBuilder.isEmpty()) {
      result.insert(0, wordBuilder + " ");
    }

    return result.deleteCharAt(result.length() - 1).toString();
  }

  @SuppressWarnings("unused")
  private static String method02(String s) {
    boolean findNonZero = false;
    LinkedList<String> words = new LinkedList<>();
    StringBuilder wordBuilder = new StringBuilder();
    for (int i = 0; i < s.length(); i++) {
      if (!findNonZero) {
        if (s.charAt(i) != ' ') {
          findNonZero = true;
          wordBuilder.append(s.charAt(i));
        }
        continue;
      }
      if (s.charAt(i) == ' ') {
        findNonZero = false;
        words.addFirst(wordBuilder.toString());
        wordBuilder.setLength(0);
      } else {
        wordBuilder.append(s.charAt(i));
      }
    }
    if (!wordBuilder.isEmpty()) {
      words.addFirst(wordBuilder.toString());
    }

    StringBuilder sb = new StringBuilder();
    for (String word : words) {
      sb.append(word).append(" ");
    }
    return sb.deleteCharAt(sb.length() - 1).toString();
  }

  /**
   * 对给定的字符串进行倒序拼接 该方法接收一个字符串参数，将其按照空格分割成多个单词， 并按照从右到左的顺序进行拼接，最后返回拼接后的字符串
   *
   * @param s 待处理的字符串
   * @return 倒序拼接后的字符串
   */
  @SuppressWarnings("unused")
  private String method01(String s) {
    String[] words = s.trim().split(" +");
    StringBuilder sb = new StringBuilder();
    for (int i = words.length - 1; i >= 1; i--) {
      sb.append(words[i]).append(" ");
    }
    sb.append(words[0]);
    return sb.toString();
  }
}
